package com.health.push.controller;

import com.health.push.dto.LoginRequest;
import com.health.push.dto.LoginResponse;
import com.health.push.dto.RegisterRequest;
import com.health.push.entity.User;
import com.health.push.service.UserService;
import com.health.push.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

@RestController
@RequestMapping("/oauth")
@CrossOrigin(origins = "*")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    private void logRequestDetails(HttpServletRequest request, String endpoint, Object requestBody) {
        logger.info("=== {} 请求详情 ===", endpoint);
        
        // 打印请求URL和方法
        logger.info("请求URL: {} {}", request.getMethod(), request.getRequestURL());
        
        // 打印所有请求头
        logger.info("请求头信息:");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            logger.info("  {}: {}", headerName, headerValue);
        }
        
        // 打印查询参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (!parameterMap.isEmpty()) {
            logger.info("查询参数:");
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                logger.info("  {}: {}", entry.getKey(), String.join(", ", entry.getValue()));
            }
        }
        
        // 打印请求体
        if (requestBody != null) {
            logger.info("请求体: {}", requestBody);
        }
        
        // 打印客户端信息
        logger.info("客户端IP: {}", request.getRemoteAddr());
        logger.info("User-Agent: {}", request.getHeader("User-Agent"));
        
        logger.info("=== {} 请求详情结束 ===", endpoint);
    }

    @PostMapping("/register")
    public R register(@RequestBody RegisterRequest request, HttpServletRequest httpRequest) {
        logRequestDetails(httpRequest, "用户注册", request);
        if (request.getUsername() == null || request.getUsername().trim().isEmpty()) {
            return R.error("用户名不能为空");
        }

        if (request.getPassword() == null || request.getPassword().trim().isEmpty()) {
            return R.error("密码不能为空");
        }

        if (userService.userExists(request.getUsername())) {
            return R.error("用户名已存在");
        }

        boolean success = userService.register(request);
        if (success) {
            return R.success("注册成功", null);
        } else {
            return R.error("注册失败");
        }
    }

    @PostMapping("/agent/checkBinding")
    public R login(@RequestBody String account, HttpServletRequest httpRequest) {
        logRequestDetails(httpRequest, "检查绑定", account);
        if (account == null || account.trim().isEmpty()) {
            return R.error("用户名不能为空");
        }

        String user = userService.checkBind(account);
        if (user != null) {
            LoginResponse response = new LoginResponse("token", user, "登录成功");
            return R.success(response);
        } else {
            return R.error(401, "用户名或密码错误");
        }
    }

    @PostMapping("/login")
    public R login(@RequestBody LoginRequest request, HttpServletRequest httpRequest) {
        logRequestDetails(httpRequest, "用户登录", request);
        if (request.getUsername() == null || request.getUsername().trim().isEmpty()) {
            return R.error("用户名不能为空");
        }

        if (request.getPassword() == null || request.getPassword().trim().isEmpty()) {
            return R.error("密码不能为空");
        }

        User user = userService.login(request);
        if (user != null) {
            String token = jwtUtil.generateToken(user.getUsername());
            LoginResponse response = new LoginResponse(token, user.getUsername(), "登录成功");
            return R.success(response);
        } else {
            return R.error(401, "用户名或密码错误");
        }
    }

    @GetMapping("/profile")
    public R getProfile(@RequestHeader("Authorization") String authHeader, HttpServletRequest httpRequest) {
        logRequestDetails(httpRequest, "获取用户信息", null);
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error(401, "请先登录");
        }

        String token = authHeader.substring(7);
        if (!jwtUtil.validateToken(token)) {
            return R.error(401, "Token无效或已过期");
        }

        String username = jwtUtil.getUsernameFromToken(token);
        User user = userService.findByUsername(username);

        if (user != null) {
            // 不返回密码
            User safeUser = new User();
            safeUser.setUsername(user.getUsername());
            safeUser.setEmail(user.getEmail());
            safeUser.setCreateTime(user.getCreateTime());
            return R.success(safeUser);
        } else {
            return R.error("用户不存在");
        }
    }
}